iT邦幫忙

2021 iThome 鐵人賽

DAY 5
0
自我挑戰組

.NET Core MVC網頁應用開發系列 第 5

.NET Core第5天_IWebHostEnvironment 的用途是捨麼?

  • 分享至 

  • xImage
  •  

IWebHostEnvironment用於在runtime期間判斷目前在捨麼環境執行

預設產生的Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MyCore0
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }

    }
}

於Configure傳入的參數可以看到
IWebHostEnvironment的蹤影(.net core 第2版的IHostingEnviroment 為其前身)
3.1後IWebHostEnvironment則變去Implement IHostingEnviroment

主要能提供目前正在執行的Web hosting Environment資訊
使用時要引入Microsoft.AspNetCore.Hosting 這個Namespace

此介面的定義:

public interface IWebHostEnvironment : Microsoft.Extensions.Hosting.IHostEnvironment

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.iwebhostenvironment?view=aspnetcore-3.1

在ASP.NET Core3.1 Default將環境分為三種:
IsDevelopment:開發環境
Checks if the current hosting environment name is Development.
預設模式,為在開發應用時期用的環境

IsStaging:暫時測試(預演)環境
Checks if the current hosting environment name is Staging.
部屬到正式生產環境中最後測試的環境

IsProduction:正式環境
Checks if the current hosting environment name is Production.

額外的第四種則是確認某一指定值是否就是目前的執行環境名
IsEnvironment :
True if the specified name is the same as the current environment, otherwise false.
Compares the current hosting environment name against the specified value.
會忽略大小寫!!

而要有這些環境擴充屬性需要有Microsoft.Extensions.Hosting此參考
上述這些Extension methods被定義於
Microsoft.AspNetCore.Hosting命名空間下的HostingEnvironmentExtensions Class中

當中定義兩屬性
https://ithelp.ithome.com.tw/upload/images/20210905/20107452tkJ2u4tbaM.png

1.WebRootPath − Path of the www folder(Gets or sets the absolute path to the directory that contains the web-servable application content files)

https://ithelp.ithome.com.tw/upload/images/20210905/20107452OxuvPF3js9.png

2.ContentRootPath − Path of the root folder which contains all the Application files(Gets or sets an IFileProvider pointing at WebRootPath.)

實際輸出觀察
Test Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MyCore0
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("1st Middleware in. \r\n");
                await context.Response.WriteAsync(String.Format("Is Development Env:{0} \r\n", env.IsDevelopment()));
                await context.Response.WriteAsync(String.Format("Is Staging Env:{0} \r\n", env.IsStaging()));
                await context.Response.WriteAsync(String.Format("Is Production Env:{0} \r\n", env.IsProduction()));
                await context.Response.WriteAsync(String.Format("Environment Name:{0} \r\n", env.EnvironmentName));
                await context.Response.WriteAsync(String.Format("Is Match Current Environment Name:{0} \r\n", env.IsEnvironment("Development")));
                await context.Response.WriteAsync(String.Format("Is Match Current Environment Name:{0} \r\n", env.IsEnvironment("Staging")));
                await context.Response.WriteAsync(String.Format("WebRootPath:{0} \r\n", env.WebRootPath));
                await context.Response.WriteAsync(String.Format("ContentRootPath:{0} \r\n", env.ContentRootPath));
                await context.Response.WriteAsync(String.Format("ApplicationName:{0} \r\n", env.ApplicationName));
            });
        }

    }
}

https://ithelp.ithome.com.tw/upload/images/20210905/20107452CEff4HyIBH.png

在這我們會發現預設是Development
這是為何呢?
我們到專案屬性面板的偵錯看到

https://ithelp.ithome.com.tw/upload/images/20210905/20107452boheeea36P.png

.Net Core於runtime期間會查一個環境變數
叫做ASPNETCORE_ENVIRONMENT,依此環境變數的值
來決定目前是不是Development或者Staging或者Production。

Ref:

[鐵人賽 Day16] ASP.NET Core 2 系列 - 多重環境組態管理 (Multiple Environments)
https://blog.johnwu.cc/article/ironman-day16-asp-net-core-multiple-environments.html

What is the role of IWebHostEnvironment interface in C# ASP.NET Core?
https://www.tutorialspoint.com/what-is-the-role-of-iwebhostenvironment-interface-in-chash-asp-net-core

ASP.NET Core 2.2 -> 3.0 upgrade. env.IsDevelopment() not found
https://stackoverflow.com/questions/58070476/asp-net-core-2-2-3-0-upgrade-env-isdevelopment-not-found

[.net core]如何在開發階段透過Visual Studio設定不同的執行環境 (環境變數)
https://blog.alantsai.net/posts/2019/01/faq-how-to-change-executing-environment-in-visual-studio#WizKMOutline_1547648931365459

本文同步發表至個人部落格
https://coolmandiary.blogspot.com/2020/11/net-coreiwebhostenvironment.html


上一篇
.NET Core第4天_middleware是捨麼?
下一篇
.NET Core第6天_如何將asp.net core應用部屬到IIS_透過visual studio
系列文
.NET Core MVC網頁應用開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言